package	com.sdry.web.controller.tdd.sale;
import java.text.DecimalFormat;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sdry.model.lz.Customer;
import com.sdry.model.tdd.sale.SaleBill;
import com.sdry.model.tdd.sale.SaleBillDetails;
import com.sdry.model.tdd.sale.SaleCustomerExpenseAccount;
import com.sdry.model.tdd.sale.SaleExpenseAccount;
import com.sdry.model.tdd.sale.SaleMaterielExpenseAccount;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.service.tdd.OthersService;
import com.sdry.service.tdd.sale.SaleBillDetailsService;
import com.sdry.service.tdd.sale.SaleBillService;
import com.sdry.service.tdd.sale.SaleCustomerExpenseAccountService;
import com.sdry.service.tdd.sale.SaleExpenseAccountService;
import com.sdry.service.tdd.sale.SaleMaterielExpenseAccountService;
import com.sdry.utils.DateUtil;
import com.sdry.utils.ResponseUtil;
import com.sdry.utils.StringUtil;
import com.sdry.web.controller.tdd.emailRecord.EmailRecordController;
/**
 *
 *@ClassName: SaleBillController
 *@Description: 对账单
 *@Author tdd
 *@Date 2019-09-27 14:31:15
 *@version 1.0
*/
@Controller
@RequestMapping("/saleBill")
public class SaleBillController{
	@Resource SaleBillService saleBillService;
	@Resource SaleBillDetailsService saleBillDetailsService;
	@Resource OthersService othersService;
	@Resource SaleExpenseAccountService saleExpenseAccountService;
	@Resource SaleMaterielExpenseAccountService saleMaterielExpenseAccountService;
	@Resource SaleCustomerExpenseAccountService saleCustomerExpenseAccountService;
	//声明一个Logger
	private final static Logger logger = LoggerFactory.getLogger(EmailRecordController.class);
	/** 
	 * 进入页面
	 * @param model
	 * @return 页面路径
	*/
	@RequestMapping("/page")
	public String pageSaleBill (Model model) {
		//供应商科目
		SaleExpenseAccount saleExpenseAccount = new SaleExpenseAccount();
		saleExpenseAccount.setEtype("1");
		saleExpenseAccount.setEisTrue("0");
		List<SaleExpenseAccount> saleExpenseAccounts = saleExpenseAccountService.queryAllByMution(saleExpenseAccount);
		model.addAttribute("saleExpenseAccounts",saleExpenseAccounts);
		//供应商
		Customer param = new Customer();
		param.setCustomer_type("0");
		List<Customer> customers = othersService.customerQueryAllByMution(param);
		model.addAttribute("customers",customers);
		return "/td/sale/saleBill";
	}
	/** 
	 * 根据主键id查询实体
	 * @param id 主键id
	 * @return 实体
	*/
	@RequestMapping("/queryById")
	@ResponseBody
	public SaleBill queryById(Long id) {
		SaleBill param = saleBillService.queryById(id);
		return param;
	}
	/** 
	 * 条件查询所有
	 * @param param 实体条件
	 * @return 实体集合
	*/
	@RequestMapping("/queryAllByMution")
	@ResponseBody
	public List<SaleBill> queryAllByMution(SaleBill param) {
		List<SaleBill> list = saleBillService.queryAllByMution(param);
		return list;
	}
	/** 
	 * 条件分页查询
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/list")
	public void list(SaleBill param,HttpServletResponse response) throws Exception{
		/*
		 * 条件分页查询内容
		 */
		List<SaleBill> list = saleBillService.findPageByMution(param);
		/*
		 * 条件查询总条数
		 */
		Integer total = saleBillService.selectCountByMution(param);
		/*
		 * 转为json数据传至页面
		 */
		//创建result
		JSONObject jsonObject = new JSONObject();
		//添加入jsonObject
		jsonObject.put("code", 0);
		jsonObject.put("rows", list);
		jsonObject.put("total", total);
		ResponseUtil.write(response, jsonObject);
	}
	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/insert")
	public void insert(SaleBill param,HttpSession httpSession, HttpServletResponse response) throws Exception{
		param.setIsReconciliation("0");
		//获取当前操作人
		ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		param.setCreateMan(su.getUserName());
		param.setCreateTime(DateUtil.dateFormat3());
		Long bid = saleBillService.insert(param);
		if(null != bid && bid > 0){
			String[] settlements = param.getSettlement().split(",");
			for (int i = 0; i < settlements.length; i++) {
				SaleBillDetails saleBillDetails = new SaleBillDetails();
				saleBillDetails.setBid(String.valueOf(bid));
				saleBillDetails.setBdisReconciliation("0");
				if("0".equals(settlements[i])){
					//税率
					saleBillDetails.setBdremark(param.getTaxRate());
					//查询需要对账信息
					String ename = "配送费";
					String whereSql = " and so.status != 0 ";
					whereSql = whereSql + " and m.customer_id = '"+param.getSid()+"' ";
					whereSql = whereSql + " and so.create_date >= '"+param.getStartTime()+"' ";
					whereSql = whereSql + " and so.create_date <= '"+param.getEndTime()+"' ";
					Integer total = saleMaterielExpenseAccountService.selectCountByMutionReport(ename, whereSql );
					List<SaleMaterielExpenseAccount> list = saleMaterielExpenseAccountService.findPageByMutionReport(1,total,ename, whereSql);
					for (SaleMaterielExpenseAccount saleMaterielExpenseAccount : list) {
						saleBillDetails.setMid(saleMaterielExpenseAccount.getMid());
						saleBillDetails.setKid(saleMaterielExpenseAccount.getKid());
						saleBillDetails.setBdnum(StringUtil.strNum(saleMaterielExpenseAccount.getNum()));
						/*float unitPrice = Float.valueOf(saleMaterielExpenseAccount.getUnitPrice());
					float dzMoney = StringUtil.strNum(saleMaterielExpenseAccount.getNum()) * unitPrice;
					DecimalFormat fnum = new DecimalFormat("##0.00");
					String bddzMoney = fnum.format(dzMoney);
					saleBillDetails.setBddzMoney(bddzMoney);*/
						saleBillDetails.setBddzMoney(saleMaterielExpenseAccount.getUnitPrice());
						saleBillDetailsService.insert(saleBillDetails);
					}
				}else if("1".equals(settlements[i])){
					//查询需要对账信息
					String ename = "运输费";
					String whereSql = " and dn.status >= 2 ";
					whereSql = whereSql + " and cu.id = '"+param.getSid()+"' ";
					whereSql = whereSql + " and so.arrival_date >= '"+param.getStartTime()+"' ";
					whereSql = whereSql + " and so.arrival_date <= '"+param.getEndTime()+"' ";
					Integer total = saleCustomerExpenseAccountService.selectCountByMutionReport(ename, whereSql);
					List<SaleCustomerExpenseAccount> list = saleCustomerExpenseAccountService.findPageByMutionReport(1,total,ename, whereSql);
					for (SaleCustomerExpenseAccount saleCustomerExpenseAccount : list) {
						//税率
						saleBillDetails.setBdremark(saleCustomerExpenseAccount.getRemark());
						
						saleBillDetails.setKid(saleCustomerExpenseAccount.getKid());
						saleBillDetails.setBdnum(StringUtil.strNum(saleCustomerExpenseAccount.getNum()));
						/*float unitPrice = Float.valueOf(saleCustomerExpenseAccount.getUnitPrice());
					float dzMoney = StringUtil.strNum(saleCustomerExpenseAccount.getNum()) * unitPrice;
					DecimalFormat fnum = new DecimalFormat("##0.00");
					String bddzMoney = fnum.format(dzMoney);
					saleBillDetails.setBddzMoney(bddzMoney);*/
						saleBillDetails.setBddzMoney(saleCustomerExpenseAccount.getUnitPrice());
						saleBillDetailsService.insert(saleBillDetails);
					}
				}else if("2".equals(settlements[i])){
					SaleCustomerExpenseAccount saleCustomerExpenseAccount = new SaleCustomerExpenseAccount();
					saleCustomerExpenseAccount.setSid(param.getSid());
					saleCustomerExpenseAccount.setIsTrue("0");
					List<SaleCustomerExpenseAccount> saleCustomerExpenseAccounts = saleCustomerExpenseAccountService.queryAllByMution(saleCustomerExpenseAccount);
					for (SaleCustomerExpenseAccount saleCustomerExpenseAccount2 : saleCustomerExpenseAccounts) {
						//税率
						saleBillDetails.setBdremark(saleCustomerExpenseAccount2.getRemark());
						
						saleBillDetails.setKid(saleCustomerExpenseAccount2.getKid());
						saleBillDetails.setBdnum(StringUtil.strNum(saleCustomerExpenseAccount2.getNum()));
						/*float unitPrice = Float.valueOf(saleCustomerExpenseAccount2.getUnitPrice());
					float dzMoney = StringUtil.strNum(saleCustomerExpenseAccount2.getNum()) * unitPrice;
					DecimalFormat fnum = new DecimalFormat("##0.00");
					String bddzMoney = fnum.format(dzMoney);
					saleBillDetails.setBddzMoney(bddzMoney);*/
						saleBillDetails.setBddzMoney(saleCustomerExpenseAccount2.getUnitPrice());
						saleBillDetailsService.insert(saleBillDetails);
					}
				}
				saleBillDetails = null;
			}
		}
		ResponseUtil.write(response,bid);
	}
	/** 
	 * 根据主键更新 返回影响行数
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/update")
	public void update(SaleBill param,HttpServletResponse response) throws Exception{
		Integer count = saleBillService.update(param);
		ResponseUtil.write(response,count);
	}
	/** 
	 * 根据主键拼接的字符串删除返回影响行数
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	*/
	@RequestMapping("/delete")
	public void delete(String ids,HttpServletResponse response) throws Exception{
		ids=ids.replace("'",""); 
		Integer count = saleBillService.delete(ids);
		if(count > 0){
			saleBillDetailsService.deleteByBid(ids);
		}
		ResponseUtil.write(response,count);
	}
	/** 
	 * 根据主键拼接的字符串修改状态返回影响行数
	 * @param ids 主键拼接的字符串
	 * @param isReconciliation 状态
	 * @return 影响行数
	 */
	@RequestMapping("/updateIsReconciliationByIds")
	public void updateIsReconciliationByIds(String ids,String isReconciliation,HttpServletResponse response) throws Exception{
		ids=ids.replace("'",""); 
		Integer count = saleBillService.updateIsReconciliationByIds(ids,isReconciliation);
		ResponseUtil.write(response,count);
	}
}
